<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Mail;
use DB;
use Crypt;

class RegController extends Controller
{
    public function reg()
    {
    	return view('home.user.reg');
    }
    //验证邮箱
    public function testEmail()
    {
    	$res = DB::table('users') -> where('email', $_GET['email']) -> first();
    	if($res)
    	{
    		return json_encode(1);
    	}else
    	{
    		return json_encode(0);
    	}
    	
    }
    //发送邮件
    public function sendEmail(Request $request)
    {
    	if(empty($_GET['email']))
    	{
    		return 1;
    	}
    	$code = rand(100000,999999);
    	Mail::send('emails.code',['code' => $code],function($message){
    		$message -> subject('时光网验证码');
    		$message -> to($_GET['email']);
    	});
    	return json_encode($code);
    }
    //添加注册信息
    public function doreg(Request $request)
    {
    	$data = $request -> except('_token');
    	$data['ctime'] = time();
    	$data['password'] = Crypt::encrypt($data['password']);

    	$data['remember_token'] = str_random(70);
    	$time = date("Y-m-d H:i:s");
    	$data['created_at'] = $time;
    	$data['updated_at'] = $time;
    	$res = DB::table('users') -> insert(['email' => $data['email'], 'password' => $data['password'], 'ctime' => $data['ctime'], 'remember_token' => $data['remember_token'], 'created_at' => $data['created_at'], 'updated_at' => $data['updated_at']]);

        if($res)
        {

            $sele = DB::table('users') -> where('email', $data['email']) -> first();

            $resd = DB::table('userdetail') -> insert(['id' => $sele -> id, 'name' => $sele -> email, 'sex' => $data['sex']]);
            if($resd)
            {
                return redirect('/');
            }else
            {
                return redirect('home/reg') -> with(['info' => '注册失败']);
            }

        }else
        {
            return redirect('home/reg') -> with(['info' => '注册失败']);
        }
    }
}
